<?php
/**
 * Created by PhpStorm.
 * User: pf
 * Date: 2017/12/8
 * Time: 14:50
 */

namespace App\Repositories;



use App\Http\Controllers\Admin\Business\Service\ComboOrder;
use App\Http\Controllers\Admin\Member\Repository\Member;
use App\MemberLog;
use App\Service\Account;
use App\Setting;
use EasyWeChat\Support\Log;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class DistributeRepository
{
    private $member;
    private $options;

    const ACT_COMBO_BUY = 1;    //购买套餐
    const ACT_DISTRIBUTE = 2;    //推荐新用户
    const ACT_FILL_INFO = 3;  //完善信息
    const ACT_GAME = 4; //参与游戏
    const ACT_SCENE_BUY = 5;//购买景点
    const ACT_WITHDRAW = 6;//提现申请


    protected function openidGetUser($openid){
        $wechat=app('wechat');
         return $wechat->user->get($openid)->toArray();
    }
    public function subscribeDistribute($openid,$leaderId){
        //查询openid
       $member= Member::where('openid',$openid)->first();
       if(!$member){
          $userInfo= $this->openidGetUser($openid);
           $member = new Member();
           $member->openid = $userInfo['openid'];
           $member->nickname = $userInfo['nickname'];
           $member->headimgurl = $userInfo['headimgurl'];
           $member->sex = $userInfo['sex'];
           $member->city = $userInfo['city'];
           $member->province = $userInfo['province'];
           $member->country = $userInfo['country'];
           $member->save();
        return    $this->distribute($leaderId,$member->id);
       }
    }
    //写入更新分销上下级关系
    public function distribute($firstLeader,$toUser){
        if($firstLeader!=$toUser){
            $leader=Member::find($firstLeader);
            $user=Member::find($toUser);
            $pid= $user->pid=$leader->id ?? 0;
            if($leader->path=='0'){
                $user->path=$leader->path.','.$leader->id.','.$user->id;
            }else{
                $user->path=$leader->path.','.$user->id;
            }
            //推广人数+1
            $leader->increment('promote_num',1);
            $user->save();
            //判断是否开启了注册奖励推广人的规则
            if(Setting::getConfig('distributeWay','分销设置')==1){
                $this->account($user->pid,self::ACT_DISTRIBUTE,['from'=>$toUser]);
            }
            return $leader;
        }
    }
    //检查是否有上级
    public function isHasLeader($user_id){
        $member=Member::find($user_id);
        if($member->pid!=0){
            return true;
        }else{
            return false;
        }
    }
   //生成分销二维码 按照id
    public function getWechatQrcode($user_id){
      return  Cache::rememberForever('qrcode'.$user_id,function ()use($user_id){
            $wechat=app('wechat');
            $qrcode=$wechat->qrcode;
            $result=$qrcode->forever($user_id);
            $ticket = $result->ticket; // 或者 $result['ticket']
            $url = $result->url;
            return $url= $qrcode->url($ticket);
        });
    }
    public function account($member_id,$type,$options=[]){
        //
        $this->member = Member::find($member_id);
        $this->options = $options;
        switch ($type){
            case self::ACT_DISTRIBUTE:
                //推广奖励
                $this->account1();
                break;
            case self::ACT_COMBO_BUY:
                //需要order_id
                $this->account2();
                break;
            case self::ACT_FILL_INFO:
                $this->account3();
                break;
            case self::ACT_GAME:
                break;
            case self::ACT_SCENE_BUY:
                $this->account5();
                break;
            case self::ACT_WITHDRAW:
                $this->account6();
                break;
        }
    }
    private function account1(){
        $money = Setting::getConfig('distributeMoney','分销设置');
        Member::where('id',$this->member->id)->increment('wallet_all_push_money',$money);
        Member::where('id',$this->member->id)->increment('wallet_push_money',$money);
        $this->account_logs($this->member->id,Account::DISTRIBUTE,$money,['from'=>$this->options['from']]);
    }
    private function account2(){
        $orderModel = new ComboOrder();
        //查出订单
        $order_id = $this->options['order_id'];
        $order = $orderModel->getComboOrder($order_id);
        //计算分销价格
        $rateAry = $this->get_real_rate($order);
        $parentMoney = $order->price*$rateAry['rate']/100;
        $topMoney = $order->price*$rateAry['top_rate']/100;
        //返上级
        if($this->member->pid!=0){
            $parent = Member::find($this->member->pid);
            //返上级
            if($parent){
                Member::where('id',$this->member->pid)->increment('wallet_all_push_money',$parentMoney);
                Member::where('id',$this->member->pid)->increment('wallet_push_money',$parentMoney);
                $data=[
                    'first_order_num'=>0,
                    'first_money'=>0,
                    'order_num'=>1,
                    'money'=>$parentMoney,
                    'nickname'=>$parent->nickname,
                    'member_id'=>$parent->id
                ];
                $this->memberLog($data);
                $this->account_logs($this->member->pid,Account::REBATE,$parentMoney,['from'=>$this->member->id]);
                if($parent->pid!=0){
                    //返回顶级
                    $leaderId = explode(',',$parent->path)[1];
                    $leader = Member::find($leaderId);
                    if($leader){
                        $data=[
                            'first_order_num'=>1,
                            'first_money'=>$topMoney,
                            'order_num'=>0,
                            'money'=>0,
                            'nickname'=>$leader->nickname,
                            'member_id'=>$leader->id
                        ];
                        $this->memberLog($data);
                        Member::where('id',$leaderId)->increment('wallet_all_push_money',$topMoney);
                        Member::where('id',$leaderId)->increment('wallet_push_money',$topMoney);
                       $this->account_logs($leaderId,Account::REBATE_TOP,$topMoney,['from'=>$this->member->id]);

                    }

                }
            }
        }
    }
    public function memberLog($data){
       $memberLog= MemberLog::where('member_id',$data['member_id'])->first();
       if($memberLog){
           $memberLog->nickname=$data['nickname'];
           $memberLog->member_id=$data['member_id'];
           $memberLog->save();
           $memberLog->increment('first_order_num',$data['first_order_num']);
           $memberLog->increment('first_money',$data['first_money']);
           $memberLog->increment('order_num',$data['order_num']);
           $memberLog->increment('money',$data['money']);
       }else{
           $memberLog=new MemberLog();
           $memberLog->nickname=$data['nickname'];
           $memberLog->member_id=$data['member_id'];
           $memberLog->first_order_num=$data['first_order_num'];
           $memberLog->first_money=$data['first_money'];
           $memberLog->order_num=$data['order_num'];
           $memberLog->money=$data['money'];
           $memberLog->save();
       }
    }
    private function account3(){
        $money = Setting::getConfig('regAward','分销设置');
        if($money>0){
            Member::where('id',$this->member->id)->increment('wallet_spots',$money);
           $this->account_logs($this->member->id,Account::FILL_INFORMATION,$money);
        }
    }
    private function account4(){

    }
    private function account5(){
        //扣次数
        Member::where('id',$this->member->id)->decrement('wallet_spots');
       $this->account_logs($this->member->id,Account::FILL_INFORMATION,-1);
    }
    private function account6(){
        $money = $this->options['money'];
        Member::where('id',$this->member->id)->decrement('wallet_push_money',$money);
        Member::where('id',$this->member->id)->increment('wallet_used_push_money',$money);
       $this->account_logs($this->member->id,Account::WITHDRAW,$money,['needApprove'=>$this->options['needApprove']]);
    }
    public function get_real_rate($order, $type=1){
        $return = [];
        $order_id = $order->id;
        $sysRate = [
            'rate'  =>  \App\Setting::getConfig('rate','分销设置'),
            'top_rate'  =>  \App\Setting::getConfig('topRate','分销设置')
        ];
        if($order->activity){
            //套餐
            $activity = new \App\Http\Controllers\Admin\Business\Service\ComboActivities();
            $actEntity = $activity->getComboActivities($order->activity->id);

            if($actEntity->rate_type == \App\Http\Controllers\Admin\Business\Service\ComboActivities::RATE_TYPE_SYS){
                $combo = new \App\Http\Controllers\Admin\Business\Service\Combo();
                $entity = $combo->getCombo($order->combo_id);
                if($entity->rate_type==\App\Http\Controllers\Admin\Business\Service\Combo::RATE_TYPE_SYS){
                    //按系统
                    $return  = $sysRate;
                }else{
                    $return = [
                        'rate'    =>  $entity->rate,
                        'top_rate'  =>  $entity->top_rate
                    ];
                }
            }else{
                $return = [
                    'rate'  =>  $actEntity->rate,
                    'top_rate'  =>  $actEntity->top_rate
                ];
            }

        }else{
            //活动
            $combo = new \App\Http\Controllers\Admin\Business\Service\Combo();
            $entity = $combo->getCombo($order->combo_id);
            if($entity->rate_type==\App\Http\Controllers\Admin\Business\Service\Combo::RATE_TYPE_SYS){
                //按系统
                $return  = $sysRate;
            }else{
                $return = [
                    'rate'    =>  $entity->rate,
                    'top_rate'  =>  $entity->top_rate
                ];
            }
        }
        return $return;
    }
   public function account_logs($member_id,$type,$money,$options=[]){
        $model = new \App\Service\Account();
        return $model->account_log($member_id,$type,$money,$options);
    }
}